from requests import get
import logging
import threading
import os
from time import sleep

count = 0
# 创建一个logger
logger = logging.getLogger('listen')
logger.setLevel(logging.DEBUG)

# 创建一个handler，用于写入日志文件
fh = logging.FileHandler('./restart.log')
fh.setLevel(logging.DEBUG)

# 再创建一个handler，用于输出到控制台
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)

# 定义handler的输出格式
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
fh.setFormatter(formatter)
ch.setFormatter(formatter)

# 给logger添加handler
logger.addHandler(fh)
logger.addHandler(ch)

"""
  TCP    192.168.1.155:63758    129.211.126.69:4730    ESTABLISHED     12884
  TCP    192.168.1.155:63973    129.211.126.69:4730    ESTABLISHED     3568
"""


# 记录日志
def sendMSG(msg):
    logger.info(msg)


# 启动CC
def startCC():
    os.chdir(os.getcwd())
    os.startfile(".\\cc.exe")


# 根据PID干掉
def kill_CC():
    find_kill = 'taskkill /f /t /im cc.exe'
    result = os.popen(find_kill)
    sendMSG(result.read())


def doCheck():
    global count
    if not checkCC():
        count = count + 1
        if count >= 2:
            kill_CC()
            sendMSG('重启了CC')
            sleep(2)
            startCC()
            count = 0
    else:
        count = 0
        sendMSG('此次请求正常')


def checkCC():
    try:
        headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) '
                          'Chrome/35.0.1916.153 Safari/537.36 SE 2.X MetaSr 1.0'}
        response = get(url='http://127.0.0.1:9877/Dual/GetALLAttendant', timeout=2, headers=headers)  # 请求超时时间为2秒
        code = response.status_code  # http请求的返回状态，若为200则表示请求成功,返回的状态码是 int类型
        if code == 200:
            return True
        else:
            return False
    except:
        return False


# start 方法
def start():
    try:
        do = threading.Thread(target=doCheck, )
        do.start()
        while do.is_alive():
            sleep(0.5)
    except Exception as r:
        logger.error(str(r))
    finally:
        threading.Timer(10, start, ()).start()


start()